package com.paypalpay.controller.pay;

import com.paypalpay.entity.common.UserboundPaymentOrder;
import com.paypalpay.entity.pay.PaypalNotificationpaymentResults;
import com.paypalpay.service.PaypalNotificationpaymentResultsService;
import com.paypalpay.service.UserboundPaymentOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping(value = "/paypal")
public class PaypalPaymenttController {
    @Resource
    PaypalNotificationpaymentResultsService paypalNotificationpaymentResultsService;

    @Resource
    private UserboundPaymentOrderService userboundPaymentOrderService;

    @Autowired
    private HttpSession session;
    private String payType = "2";
    public static final String paySuccess = "http://wx.linksfield.net/#/paySuccess";
    public static final String payError = "http://wx.linksfield.net/#/payError";
    private Logger log = LoggerFactory.getLogger(getClass());

    //paypal支付请求的链接是：http://wx.linksfield.net/paypalpay/paypal/paypals?deviceId=99999&deviceType=4&orderId=111111111111&amount=0.01&partnerCode=00001&packageCode=PACKAGE20180502000013&orderPeriod=1&orderUnit=2&paymentOrderId=20181023110811442&currencyCode=CNY&isOpen=1
    //请求发起支付
    @CrossOrigin
    @RequestMapping(value = "/paypals")
    public String paypalPay(HttpServletRequest request) {
        System.out.println("paypal支付请求的链接是：" + request.getRequestURL() + "?" + request.getQueryString());
        //需要前端发这三个参数上来 String deviceId = (String) session.getAttribute("deviceId");
        String deviceId = request.getParameter("deviceId");
        String deviceType = request.getParameter("deviceType");
        String orderId = request.getParameter("orderId");
        String amount = request.getParameter("amount");
        String currency_code = request.getParameter("currencyCode");
        String partnerCode = request.getParameter("partnerCode");
        String packageCode = request.getParameter("packageCode");
        String orderPeriod = request.getParameter("orderPeriod");
        String orderUnit = request.getParameter("orderUnit");
        String isOpen = request.getParameter("isOpen");
        String paymentOrderId = request.getParameter("paymentOrderId");
        String requestOrderId = request.getParameter("requestOrderId");

        System.out.println("deviceId：" + deviceId + ";orderId:" + orderId + ";paymentOrderId:" + paymentOrderId + ";requestOrderId:" + requestOrderId);
        if (deviceType == null || deviceId == null || orderId == null || amount == null || currency_code == null || partnerCode == null || packageCode == null || orderPeriod == null || orderUnit == null || paymentOrderId == null || isOpen == null) {
            System.out.println("参数不齐全");
        }
//        else {
//            System.out.println("参数至少是齐全的");
//            // 根据packageCode去查询一下当前用户购买的套餐名称，并且插入到数据库
//            String packageName = "";
//            System.out.println("packageCode是什么多少：" + packageCode);
//            if (packageCode.contains(",") == true) {
//                // 此情况说明packageCode有多个套餐
//                String[] str = packageCode.split(",");
//                for (int i = 0; i < str.length; i++) {
//                    String packages = str[i];
//                    packageName += userboundPaymentOrderService.getPackageNameBypackages(packages,partnerCode) + ",";
//                    System.out.println("取到的套餐名称：" + packageName);
//                }
//            } else {
//                System.out.println("开始取name");
//                //根据前面得到的code去数据库查询name
//                //packageName = internationalPayPackageService.getPackageNameBypackageCode(packageCode);
//                packageName = userboundPaymentOrderService.getPackageNameByPackageCode(packageCode,partnerCode);
//                System.out.println("取到的套餐名称：" + packageName);
//            }

//            if (!orderId.equals("") && !"undefined".equals(orderId)) {
            //paypal支付当然是非微信用户访问
//                System.out.println("paypal支付支付前入库！");
//                UserboundPaymentOrder paymentOrder = new UserboundPaymentOrder();
//                paymentOrder.setPartnerCode(partnerCode);
//                paymentOrder.setPackageCode(packageCode);
//                paymentOrder.setPackageName(packageName);
//                paymentOrder.setPaymentOrderId(paymentOrderId);
//                paymentOrder.setOrderId(orderId);
//                paymentOrder.setDeviceId(deviceId);
//                paymentOrder.setAmount(amount);
//                paymentOrder.setOrderPeriod(orderPeriod);
//                paymentOrder.setOrderUnit(orderUnit);
//                paymentOrder.setIsOpen(isOpen);
//                paymentOrder.setPayType(payType);
//                paymentOrder.setOrderCurrency(currency_code);
//                // 根据收到的deviceId去更新数据表，deviceId此时是有的，所以不能为null,openid为空
//                userboundPaymentOrderService.updateUserboundNotWeixinPaymentOrder(paymentOrder);

//                System.out.println("paypal支付支付前入库！");
//                int c = userboundPaymentOrderService.findOrderIdAndDeviceId(paymentOrderId, orderId, deviceId, amount);
//
//                if (c > 0) {
//                    //数据库有空行
//                    System.out.println("paypal支付更新数据记录！");
//                    UserboundPaymentOrder paymentOrder = new UserboundPaymentOrder();
//                    paymentOrder.setPartnerCode(partnerCode);
//                    paymentOrder.setPackageCode(packageCode);
//                    paymentOrder.setPackageName(packageName);
//                    paymentOrder.setRequestOrderId(requestOrderId);
//                    paymentOrder.setPaymentOrderId(paymentOrderId);
//                    paymentOrder.setOrderId(orderId);
//                    paymentOrder.setDeviceId(deviceId);
//                    paymentOrder.setAmount(amount);
//                    paymentOrder.setOrderPeriod(orderPeriod);
//                    paymentOrder.setOrderUnit(orderUnit);
//                    paymentOrder.setIsOpen(isOpen);
//                    paymentOrder.setPayType(payType);
//                    paymentOrder.setOrderCurrency(currency_code);
//                    // 根据收到的deviceId去更新数据表，deviceId此时是有的，所以不能为null,openid为空
//                    userboundPaymentOrderService.updateUserboundNotWeixinPaymentOrder(paymentOrder);
//                } else {
//                    //数据库没有这条数据，自己加一条
//                    System.out.println("paypal支付多写一条记录！");
//                    UserboundPaymentOrder paymentOrder = new UserboundPaymentOrder();
//                    paymentOrder.setPartnerCode(partnerCode);
//                    paymentOrder.setPackageCode(packageCode);
//                    paymentOrder.setPackageName(packageName);
//                    paymentOrder.setRequestOrderId(requestOrderId);
//                    paymentOrder.setPaymentOrderId(paymentOrderId);
//                    paymentOrder.setOrderId(orderId);
//                    paymentOrder.setDeviceId(deviceId);
//                    paymentOrder.setDeviceType(deviceType);
//                    paymentOrder.setAmount(amount);
//                    paymentOrder.setOrderPeriod(orderPeriod);
//                    paymentOrder.setOrderUnit(orderUnit);
//                    paymentOrder.setIsOpen(isOpen);
//                    paymentOrder.setPayType(payType);
//                    paymentOrder.setOrderCurrency(currency_code);
//                    // 根据收到的deviceId去更新数据表，deviceId此时是有的，所以不能为null,openid为空
//                    userboundPaymentOrderService.InsertUserboundNotWeixinPaymentOrder(paymentOrder);
//
//                }
//            }


 //       }
        return null;
    }

    @RequestMapping(value = "/notifyCallback")
    @CrossOrigin
    public String notifyCallback(HttpServletRequest request, @RequestBody String requestStr) {
        System.out.println("paypal回调的内容是：" + request.getRequestURL() + "?" + request.getQueryString());
        try {
            request.setCharacterEncoding("utf-8");
            System.out.println("请求的报文体：" + requestStr);
            //把大的字符串按照&分割，分成a=b的形式
            String[] strs = requestStr.split("&");

            String mc_gross = strs[0].toString();
            System.out.println("金额：" + mc_gross);
            //再把a=b的形式取出=后面的值
            String[] str = mc_gross.split("=");
            String amount = str[1].toString();
            System.out.println("真正金额：" + amount);

            String invoice = strs[1].toString();
            System.out.println("订单：" + invoice);
            //再把a=b的形式取出=后面的值
            String[] st = invoice.split("=");
            String orderNumber = st[1].toString();
            System.out.println("真正的订单号：" + orderNumber);

            String payment_status = strs[7].toString();
            System.out.println("" + payment_status);
            String[] payment = payment_status.split("=");
            String paymentStatus = payment[1].toString();
            System.out.println("真正的status：" + paymentStatus);

            String txn_id = strs[23].toString();
            System.out.println("应该是paypal的订单号：" + txn_id);
            String[] tx = txn_id.split("=");
            String txnId = tx[1].toString();
            System.out.println("paypal回传的真正的订单号：" + txnId);

            String mc_currency = strs[32].toString();
            System.out.println("付款货币：" + mc_currency);
            String[] currency = mc_currency.split("=");
            String mcCurrency = currency[1].toString();
            System.out.println("真正付款的货币：" + mcCurrency);

            String protection_eligibility = strs[2].toString();
            System.out.println(protection_eligibility);

            String address_status = strs[3].toString();
            System.out.println(" " + address_status);
            String payer_id = strs[4].toString();
            System.out.println("" + payer_id);
            String address_street = strs[5].toString();
            System.out.println("" + address_street);


            String payment_date = java.net.URLDecoder.decode(strs[6].toString(), "utf-8");
            System.out.println(" " + payment_date);

            String charset = strs[8].toString();
            System.out.println("" + charset);

            String address_zip = strs[9].toString();
            System.out.println(" " + address_zip);
            String first_name = strs[10].toString();
            System.out.println("" + first_name);
            String mc_fee = strs[11].toString();
            System.out.println("" + mc_fee);

            String address_country_code = strs[12].toString();
            System.out.println(" " + address_country_code);
            String address_name = strs[13].toString();
            System.out.println("" + address_name);
            String notify_version = strs[14].toString();
            System.out.println("" + notify_version);

            String custom = strs[15].toString();
            System.out.println(" " + custom);
            String payer_status = strs[16].toString();
            System.out.println("" + payer_status);
            String business = strs[17].toString();
            System.out.println("" + business);

            String address_country = strs[18].toString();
            System.out.println(" " + address_country);
            String address_city = strs[19].toString();
            System.out.println("" + address_city);
            String quantity = strs[20].toString();
            System.out.println("" + quantity);

            String verify_sign = strs[21].toString();
            System.out.println(" " + verify_sign);
            String payer_email = strs[22].toString();
            System.out.println("" + payer_email);

            String payment_type = strs[24].toString();
            System.out.println(" " + payment_type);
            String last_name = strs[25].toString();
            System.out.println("" + last_name);
            String address_state = strs[26].toString();
            System.out.println("" + address_state);

            String receiver_email = strs[27].toString();
            System.out.println(" " + receiver_email);
            String payment_fee = strs[28].toString();
            System.out.println("" + payment_fee);
            String receiver_id = strs[29].toString();
            System.out.println("" + receiver_id);


            String txn_type = strs[30].toString();
            System.out.println(" " + txn_type);
            String item_name = strs[31].toString();
            System.out.println("" + item_name);


            String item_number = strs[33].toString();
            System.out.println(" " + item_number);
            String residence_country = strs[34].toString();
            System.out.println("" + residence_country);
            String receipt_id = strs[35].toString();
            System.out.println("" + receipt_id);

            String transaction_subject = strs[36].toString();
            System.out.println(" " + transaction_subject);
            String payment_gross = strs[37].toString();
            System.out.println("" + payment_gross);
            String ipn_track_id = strs[38].toString();
            System.out.println("" + ipn_track_id);

            //将paypal回传的交易记录入库保存下来
            int c = userboundPaymentOrderService.findCountByOrderNumber(orderNumber);
            if (c <= 0) {
                //入库
                PaypalNotificationpaymentResults results = new PaypalNotificationpaymentResults();
                results.setMc_gross(mc_gross);
                results.setAmount(amount);
                results.setOrderNumber(orderNumber);
                results.setInvoice(invoice);
                results.setPayment_status(payment_status);
                results.setPaymentStatus(paymentStatus);
                results.setMc_currency(mc_currency);
                results.setMcCurrency(mcCurrency);
                results.setTxn_id(txn_id);
                results.setTxnId(txnId);
                results.setProtection_eligibility(protection_eligibility);
                results.setAddress_status(address_status);
                results.setPayer_id(payer_id);
                results.setAddress_street(address_street);
                results.setPayment_date(payment_date);
                results.setCharset(charset);
                results.setAddress_zip(address_zip);
                results.setFirst_name(first_name);
                results.setMc_fee(mc_fee);
                results.setAddress_country_code(address_country_code);
                results.setAddress_name(address_name);
                results.setNotify_version(notify_version);
                results.setCustom(custom);
                results.setPayer_status(payer_status);
                results.setBusiness(business);
                results.setAddress_country(address_country);
                results.setAddress_city(address_city);
                results.setQuantity(quantity);
                results.setVerify_sign(verify_sign);
                results.setPayer_email(payer_email);
                results.setPayment_type(payment_type);
                results.setLast_name(last_name);
                results.setAddress_state(address_state);
                results.setReceiver_email(receiver_email);
                results.setPayment_fee(payment_fee);
                results.setReceipt_id(receiver_id);
                results.setTxn_type(txn_type);
                results.setItem_name(item_name);
                results.setItem_number(item_number);
                results.setResidence_country(residence_country);
                results.setReceipt_id(receipt_id);
                results.setTransaction_subject(transaction_subject);
                results.setPayment_gross(payment_gross);
                results.setIpn_track_id(ipn_track_id);
                userboundPaymentOrderService.insertPaymentResultsPaypal(results);
                System.out.println("payapal回调信息入库完成！");
            }
            //回调的订单是成功的才要入库啊操作
            if ("Completed".equalsIgnoreCase(paymentStatus)) {
                System.out.println("进来没有？");
                //查询数据库中当前这条数据插入过没有
                int count = userboundPaymentOrderService.findRecordByInvoice(orderNumber);
                System.out.println("查询到的值：" + count);
                //说明当前没有插入记录 ，现在就去插入
                if (count <= 0) {
                    //支付方式：1-公众号支付，2-paypal，3-oceanpay，4-H5微信支付
                    UserboundPaymentOrder order = new UserboundPaymentOrder();
                    order.setPaymentOrderId(orderNumber);
                    order.setPayType("2");
                    order.setAmount(amount);
                    order.setOrderCurrency(mcCurrency);
                    order.setPayRst("success");
                    userboundPaymentOrderService.UpdatePaypalNotify(order);
                    System.out.println("数据入库完成!");

                    //入库完成就要去通知北京当前订单的支付结果
                    UserboundPaymentOrder userOrder = userboundPaymentOrderService.queryOrderByPaymentId(orderNumber);
                    if (userOrder == null) {
                        System.out.println("没有查询到需要去做支付结果通知的数据！");
                    } else {
                        String partnerCode = userOrder.getPartnerCode();
                        String orderId = userOrder.getOrderId();
                        String DeviceId = userOrder.getDeviceId();
                        String DeviceType = userOrder.getDeviceType();
                        System.out.println("查询到的订单orderId是:" + orderId + ";DeviceId是:" + DeviceId + ";DeviceType是:" + DeviceType);

                        if (orderId != null && orderId.length() > 0) {
                            System.out.println("调用给北京回调支付通知的controller!");
                            //String orderId, String deviceId, String deviceType, String payType, String payAmount
                            //return "/payNotify?orderId=" + orderId + "&deviceId=" + DeviceId + "&deviceType=" + DeviceType + "&payType=" + payType + "&payAmount=" + amount + "";
                            return "forward:/payNotify?orderId=" + orderId + "&deviceId=" + DeviceId + "&deviceType=" + DeviceType + "&payType=" + payType + "&payAmount=" + amount + "" + "&partnerCode=" + partnerCode + "";
                        }
                    }

                } else {
                    //插入过当前数据
                    System.out.println("数据已经有这条数据了！");
                }
            } else {
                //订单状态不是完成的状态
                System.out.println("payment_status是多少:" + payment_status);
            }

        } catch (Exception e) {

        }
        return null;
    }


}